import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class Refresher<T> {
  Mode? mode;
  IRefresher? refresherImpl;
  bool enablePullDown;
  bool enablePullUp;
  Widget header;
  Widget footer;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List<T>? data;
  SmartRefresher? smartRefresher;
  List<Widget>? extraHeader;
  final void Function(T, int)? buildItem;

  Refresher(this.refresherImpl, {
    this.enablePullDown: true,
    this.enablePullUp: true,
    this.header: const MaterialClassicHeader(),
    this.footer: const ClassicFooter(),
    this.extraHeader,
    this.buildItem
  }) {
    // this.data = [];
  }

  Widget build(Widget? content) {
    smartRefresher = SmartRefresher(
        // scrollDirection: Axis.vertical,
        // shrinkWrap: true,

        enablePullDown: this.enablePullDown,
        enablePullUp: this.enablePullUp,
        header: this.header,
        footer: this.footer,
        controller: _refreshController,
        onRefresh: refresherImpl?.onRefresh,
        onLoading: refresherImpl?.onLoadMore,
        child: content);
    return this.smartRefresher!;
  }

  void load(List<T>? data) {
    if (this.data == null) {
      this.data = [];
    }
    if (mode == Mode.refresh) {
      mode = Mode.none;
      this.data?.clear();
      this.enablePullUp = true;
    }
    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
    if (data?.isNotEmpty == true) {
      if (mode == Mode.loadPrevious) {
        this.data?.insertAll(0, data!);
      } else {
        this.data?.addAll(data!);
      }
    } else {
      if (mode == Mode.loadMore) {
        _refreshController.loadNoData();
        refresherImpl?.finishLoadMoreWithNoMoreData();
        this.enablePullUp = false;
      }
    }
  }

  void insert2First(T? t) {
    if (this.data == null) {
      this.data = [];
    }
    if (t == null) return;
    this.data?.insert(0, t);
  }

  void finish() {
    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
  }
}

abstract class IRefresher {
  void onLoadMore();

  void onRefresh();

  void finishLoadMoreWithNoMoreData();
}

enum Mode {
  none, //无模式，
  refresh, //下拉刷新
  loadMore, //上拉加载更多
  loadPrevious //下拉加载更多
}
